﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace Sharp_Explorer
{
    public partial class TabPanel : UserControl
    {
        List<Thread> searchThreads = new List<Thread>();
        SExplorer refToExpl;
        string lastClickedNode; string LastPath;

        public TabPanel(SExplorer re)
        {
            InitializeComponent();
            refToExpl = re;
        }

        private void initIcons()
        {
            string testFile = @"H:\Programs\CSharp\tabbing\RAW_Images\32.ico";
            string Files = @"H:\Programs\CSharp\tabbing\RAW_Images\OK.ico";

            
            //iconList.Images.Add("Directory",Image.FromFile(testFile)); //Testing, SubNodeAdder calls 32.ico directly.
            //iconList.Images.Add("File", Image.FromFile(Files));
        }
        public delegate void subNodeAdd(TreeView whichTree, TreeNode parentNode, object toAdd, string icoType);

        private void subNodeAdder(TreeView whichTree, TreeNode parentNode, object toAdd, string icoType)
        {


            if (whichTree.InvokeRequired)
            {
                if (!parentNode.Nodes.ContainsKey(Path.GetFileName(toAdd.ToString())))
                {
                    subNodeAdd safe = new subNodeAdd(subNodeAdder);
                    this.Invoke(safe, new object[] { whichTree, parentNode, toAdd, icoType });
                }
            }
            else
            {
                TreeNode thisParent = parentNode.Parent;

                parentNode.Nodes.Add(toAdd.ToString(), Convert.ToString(toAdd));
                parentNode.ImageKey = icoType;
                parentNode.SelectedImageKey = icoType;
                parentNode.Expand();
            }

        }

        private void computerToolStripMenuItem_Click(object sender, EventArgs e)
        {

            string newComputerName;
            using (ComputerIn newComputer = new ComputerIn())
            {
                newComputer.ShowDialog();
                newComputerName = newComputer.results;

            }

            if (newComputerName != null & newComputerName != "")
                treeUpdater(newComputerName);
        
        }

        public delegate void TreeList(object toAdd);

        private void treeUpdater(object toAdd)
        {
            if (this.treDirectory.InvokeRequired)
            {
                TreeList update = new TreeList(treeUpdater);
                this.Invoke(update, new object[] { toAdd });
            }
            else
            {
                treDirectory.Nodes.Add(Convert.ToString(toAdd));
            }
        }

        private void TabPanel_Load(object sender, EventArgs e)
        {
            this.initIcons();
        }

        public void reader(TreeView whichTree, TreeNode cNode)
        {
            string goodPath = FormClasses.getPathfromNode(cNode);

            TreeNode saveNode = cNode;

            FileAttributes itemIs = File.GetAttributes(goodPath);

            
                try
                {
                    List<String> list = new List<string>(Directory.GetDirectories(goodPath));
                    List<String> Files = new List<string>(Directory.GetFiles(goodPath));

                    foreach (String item in list)
                    {
                        subNodeAdder(whichTree, saveNode, Path.GetFileName(item), "Directory");
                    }

                    foreach (String item in Files)
                    {
                        subNodeAdder(whichTree, saveNode, Path.GetFileName(item), "File");
                    }
                }

                catch (DirectoryNotFoundException DirErr)
                { MessageBox.Show(DirErr.Message); }
                catch (UnauthorizedAccessException AccErr)
                { MessageBox.Show(AccErr.Message); }
                catch (IOException err)
                { MessageBox.Show(err.Message); }
            

        }

        private void treDirectory_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            string goodPath = FormClasses.getPathfromNode(e.Node);

            FileAttributes itemIs = File.GetAttributes(goodPath);

            if ((itemIs & FileAttributes.Directory) == FileAttributes.Directory)
             {
                Thread newSearcher = new Thread(() => reader(treDirectory, e.Node));
                searchThreads.Add(newSearcher);
                newSearcher.Start();
             }
            else
            {
                FilePreview(goodPath);
            }
        }

        private void fileHandler(string FilePathofFile)
        {
            List<String> TXTextensions = new List<string>
            {
                ".txt"
            };
            //legacy remove if no breakage

            DirectoryInfo file = new DirectoryInfo(FilePathofFile);


            if (TXTextensions.Contains(Convert.ToString(file.Extension)))
            {
                //string newPath = FormClasses.getPathfromNode(e.Node);

                Thread TXTReader = new Thread(() =>
                txtWriter(FilePathofFile));

                searchThreads.Add(TXTReader);
                TXTReader.Start();
            }
        }

        private void txtWriter(string File)
        {
            SExplorer write = new SExplorer();
            write.txtSafeWrite(File);
        }

        private void treDirectory_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            lastClickedNode = e.Node.FullPath;
            LastPath = FormClasses.getPathfromNode(e.Node);
            if ((Helper.TextExtensions.Exists(x => x == Path.GetExtension(lastClickedNode))) || (Helper.ImageExtensions.Exists(x => x == Path.GetExtension(lastClickedNode))))
                previewToolStripMenuItem.Enabled = true;
            else
                previewToolStripMenuItem.Enabled = false;

            if(Helper.CompressionExtensions.Exists(x => x == Path.GetExtension(lastClickedNode)))
                unpackToolStripMenuItem.Enabled = true;
            else
                unpackToolStripMenuItem.Enabled = false;
        }

        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FilePreview();
        }

        private void FilePreview()
        {
            if (Helper.ImageExtensions.Exists(x => x == Path.GetExtension(LastPath)))
            {
                ImageViewer imgViewer = new ImageViewer(LastPath);
                imgViewer.Show();
            }
            else
            {
                refToExpl.addTexttoRTB(FormClasses.readFile(LastPath));
            }
        }

        private void FilePreview(string fromFilePath)
        {
            if (Helper.ImageExtensions.Exists(x => x == Path.GetExtension(fromFilePath)))
            {
                ImageViewer imgViewer = new ImageViewer(fromFilePath);
                imgViewer.Show();
            }
            else
            {
                refToExpl.addTexttoRTB(FormClasses.readFile(LastPath));
            }
        }

        private void unpackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Helper.CompressionExtensions.Exists(x => x == Path.GetExtension(LastPath)))
            {
                string path = string.Empty;
                DialogResult result = unpackFolderBrowserDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    path = unpackFolderBrowserDialog.SelectedPath;
                }

                refToExpl.unpackFile(LastPath, path, Path.GetExtension(LastPath));
            }
        }

    }
}
